﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using DataModel;
using BasicDataManagement;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Threading;
using System.Xml;

namespace Cashier
{
    /// <summary>
    /// Interaction logic for OrderWindow.xaml
    /// </summary>
    public partial class OrderWindow : Window
    {
        public class BillItemHistory
        {
            public string DishName { get; set; }
            public decimal DishPrice { get; set; }
        }
        public class BillHistory
        {
            public List<BillItemHistory> BillItems { get; set; }
            public BillHistory()
            {
                BillItems = new List<BillItemHistory>();
            }
        }
        List<BillHistory> BillHistoryList;

        List<string> sellOffList;
        //OperatingFactory factory;
        //IOperating op;
        //Food foodlist;
        string cashierip;
        bool regOK;
        Random rand;
        private IShare serverObj;

        BasicDataManagement.IOpertation dataOp;

        List<CategoryDishplayObject> catList;

        ObservableCollection<BillItem> billItemList;
        BillItem currentBill;

        System.Windows.Media.Brush defaultBtnBG;

        Button btnCat;
        Button btnDish;
        Button btnComp;
        int compNum;
        Button btnCompFd;
        List<Button> btnOpts;
        List<string> comboFdSelectedList;

        GroupBox[] groupList;
        WrapPanel[] panelList;
        Button[] selectedFdBtn;
        int selectedCount;
        int totalSelection;

        string firsttime;

        SystemUser user;

        //WPFClient.Window1 win;

        private OrderWindow()
        {
            InitializeComponent();

            billItemList = new ObservableCollection<BillItem>();
            currentBill = new BillItem();

            listViewBill.ItemsSource = billItemList;

            //win = new WPFClient.Window1();
            BillHistoryList = new List<BillHistory>();
            sellOffList = new List<string>();

            XElement xmlfile = XElement.Load("Configuration.xml");
            cashierip = xmlfile.Element("ThisIP").Value;
        }

        public OrderWindow(SystemUser user)
            : this()
        {
            this.user = user;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            groupList = new GroupBox[5];
            panelList = new WrapPanel[5];
            groupList[0] = comboFdGB1;
            groupList[1] = comboFdGB2;
            groupList[2] = comboFdGB3;
            groupList[3] = comboFdGB4;
            groupList[4] = comboFdGB5;
            panelList[0] = comboFdPanel1;
            panelList[1] = comboFdPanel2;
            panelList[2] = comboFdPanel3;
            panelList[3] = comboFdPanel4;
            panelList[4] = comboFdPanel5;
            selectedFdBtn = new Button[5];

            catBtnsPanel.Children.Clear();

            catList = new List<CategoryDishplayObject>();
            dataOp = BasicDataManagement.OperationFactory.Create();
            var fDishCats = dataOp.LoadFixedDishCategory();
            foreach (var t in fDishCats)
            {
                catList.Add(new CategoryDishplayObject() { CategoryName = t, BelongedType = "FixedDish" });
            }

            var rDishCats = dataOp.LoadReplaceableDishCategory();
            foreach (var t in rDishCats)
            {
                catList.Add(new CategoryDishplayObject() { CategoryName = t, BelongedType = "ReplaceableDish" });
            }

            var comboCats = dataOp.LoadComboCategory();
            foreach (var t in comboCats)
            {
                catList.Add(new CategoryDishplayObject() { CategoryName = t, BelongedType = "Combo" });
            }

            foreach (var t in catList)
            {
                Button tmpCatBtn = new Button();
                tmpCatBtn.DataContext = t;
                AccessText tmpAccTxt = new AccessText();
                tmpAccTxt.SetBinding(AccessText.TextProperty, new Binding("CategoryName"));
                tmpCatBtn.Content = tmpAccTxt;
                tmpCatBtn.SetBinding(Button.ContentProperty, new Binding("CategoryName"));
                tmpCatBtn.Height = 55;
                tmpCatBtn.Width = 100;
                tmpCatBtn.Click += new RoutedEventHandler(btnCat_Click);
                catBtnsPanel.Children.Add(tmpCatBtn);
                if (defaultBtnBG == null)
                {
                    defaultBtnBG = tmpCatBtn.Background;
                }
            }

            //win.Connect(user.StaffName);
            //regOK = false;
            //rand = new Random();
            //while (!regOK)
            //{
            //    try
            //    {
            //        HttpChannel chanel = new HttpChannel(rand.Next(65535));
            //        ChannelServices.RegisterChannel(chanel);
            //        serverObj = (IShare)Activator.GetObject(typeof(IShare), "http://127.0.0.1:6666/kitchen.soap");
            //        regOK = true;
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine(ex.Message);
            //    }

            //}
        }

        void btnCat_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show((sender as Button).Background.ToString());
            if (btnCat != null)
            {
                btnCat.Background = defaultBtnBG;
            }
            btnCat = sender as Button;
            btnCat.Background = Brushes.Red;

            btnDish = null;
            btnComp = null;
            btnOpts = null;
            btnCompFd = null;



            gridDish.RowDefinitions[2].Height = new GridLength(0);
            gridDish.RowDefinitions[3].Height = new GridLength(0);
            for (int i = 4; i < 9; i++)
            {
                selectedFdBtn[i - 4] = null;
                gridDish.RowDefinitions[i].Height = new GridLength(0);
            }
            //MessageBox.Show((sender as Button).DataContext.GetType().ToString());
            List<string> dishNames = new List<string>();
            List<DishDisplayObject> dishList=new List<DishDisplayObject>();
            string catName=((sender as Button).DataContext as CategoryDishplayObject).CategoryName;
            string belongedType = ((sender as Button).DataContext as CategoryDishplayObject).BelongedType;
            switch (belongedType)
            {
                case "FixedDish":
                    {
                        dishNames = dataOp.LoadFixedDishItemName(catName);
                        break;
                    }
                case "Combo":
                    {
                        dishNames = dataOp.LoadComboItemName(catName);
                        break;
                    }
                case "ReplaceableDish":
                    {
                        dishNames = dataOp.LoadReplaceableDishItemName(catName);
                        break;
                    }
                default: break;
            }

            dishBtnsPanel.Children.Clear();

            foreach (var t in dishNames)
            {
                DishButton tmpDishBtn = new DishButton();
                DishDisplayObject tmpDishObj = new DishDisplayObject() { DishName = t, BelongedType = belongedType };
                tmpDishBtn.btnDish.DataContext = tmpDishObj;
                tmpDishBtn.Width = 160;
                tmpDishBtn.Height = 80;
                if (sellOffList.Contains(t))
                {
                    tmpDishBtn.IsEnabled = false;
                }
                tmpDishBtn.btnDish.Click += new RoutedEventHandler(btnDish_Click);
                dishBtnsPanel.Children.Add(tmpDishBtn);
                //dishNames
            }
        }

        void btnDish_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show((sender as Button).Parent.GetType().ToString());
            if (btnDish != null)
            {
                btnDish.Background = defaultBtnBG;
            }
            btnDish = sender as Button;
            btnDish.Background = Brushes.BlueViolet;

            btnComp = null;
            btnOpts = null;
            btnCompFd = null;

            gridDish.RowDefinitions[4].Height = new GridLength(0);
            gridDish.RowDefinitions[5].Height = new GridLength(0);
            gridDish.RowDefinitions[6].Height = new GridLength(0);
            gridDish.RowDefinitions[7].Height = new GridLength(0);
            gridDish.RowDefinitions[8].Height = new GridLength(0);
            for (int i = 0; i < 5; i++)
            {
                selectedFdBtn[i] = null;
            }

            Button source = e.Source as Button;
            string dishType = (source.DataContext as DishDisplayObject).BelongedType;
            if (dishType == "ReplaceableDish")
            {
                List<string> options;
                gridDish.RowDefinitions[2].Height = new GridLength(150);
                options = dataOp.LoadReplaceableDishItemOptionNames((source.DataContext as DishDisplayObject).DishName);
                OptOrCompPanel.Children.Clear();
                btnOpts = new List<Button>();
                foreach (var t in options)
                {
                    Button tmpBtn = new Button();
                    tmpBtn.Height = 50;
                    tmpBtn.Width = 130;
                    tmpBtn.Content = t;
                    if (sellOffList.Contains(t))
                    {
                        tmpBtn.IsEnabled = false;
                    }
                    tmpBtn.Click += new RoutedEventHandler(optBtn_Click);
                    OptOrCompPanel.Children.Add(tmpBtn);
                }
            }
            else if (dishType == "Combo")
            {
                List<string> components;
                //gridDish.RowDefinitions[2].Height = new GridLength(150);
                gridDish.RowDefinitions[3].Height = new GridLength(0);
                components = dataOp.LoadComboItemComponentNames((source.DataContext as DishDisplayObject).DishName);
                OptOrCompPanel.Children.Clear();

                comboFdSelectedList = new List<string>();
                compNum = components.Count();

                selectedFdBtn[0] = null;
                selectedFdBtn[1] = null;
                selectedFdBtn[2] = null;
                selectedFdBtn[3] = null;
                selectedFdBtn[4] = null;

                //以下为显示各个组分换品
                int compCount = components.Count;
                if (compCount > 5)
                {
                    compCount = 5;
                }
                selectedCount = 0;
                totalSelection = compCount;

                for (int i = 0; i < compCount; i++)
                {
                    var t = components[i];
                    gridDish.RowDefinitions[4 + i].Height = new GridLength(100);
                    groupList[i].Header = t;

                    Console.WriteLine("套餐---" + t);
                    List<string> fdList = dataOp.LoadComboItemComponentIngredientNames((source.DataContext as DishDisplayObject).DishName, t);
                    panelList[i].Children.Clear();
                    foreach (var a in fdList)
                    {
                        Console.WriteLine("   单品---" + a);
                        Button tmpBtn = new Button();
                        tmpBtn.Content = a;
                        tmpBtn.Height = 50;
                        tmpBtn.Width = 130;
                        tmpBtn.DataContext = (object)i;
                        if (sellOffList.Contains(a))
                        {
                            tmpBtn.IsEnabled = false;
                        }
                        tmpBtn.Click+=new RoutedEventHandler(btnComboFd_Click);
                        panelList[i].Children.Add(tmpBtn);
                    }
                }
                return;

                foreach (var t in components)
                {
                    ComboComponentDisplayObject ccdo = new ComboComponentDisplayObject() { ComponentName = t, BelongedComboName = (source.DataContext as DishDisplayObject).DishName };
                    Button tmpBtn = new Button();
                    tmpBtn.Height = 50;
                    tmpBtn.Width = 130;
                    tmpBtn.DataContext = ccdo;
                    tmpBtn.SetBinding(Button.ContentProperty, new Binding("ComponentName"));
                    tmpBtn.Click += new RoutedEventHandler(componentBtn_Click);
                    OptOrCompPanel.Children.Add(tmpBtn);
                }
            }
            else
            {
                gridDish.RowDefinitions[2].Height = new GridLength(0);
            }
        }

        void btnComboFd_Click(object sender, RoutedEventArgs e)
        {
            int index = (int)((sender as Button).DataContext);
            Button origin = selectedFdBtn[index];
            if (origin != null)
            {
                origin.Background = defaultBtnBG;
            }
            selectedFdBtn[index] = sender as Button;
            selectedFdBtn[index].Background = Brushes.Aqua;
        }

        void optBtn_Click(object sender, RoutedEventArgs e)
        {
            Button source = sender as Button;
            //MessageBox.Show("Same as default bg:" + (source.Background.Equals(defaultBtnBG) ? "Yes" : "No"));
            if (source.Background.Equals(defaultBtnBG))
            {
                source.Background = Brushes.Green;
                btnOpts.Add(source);
            }
            else
            {
                source.Background = defaultBtnBG;
                btnOpts.Remove(source);
            }
            //调试
            foreach (var t in btnOpts)
            {
                Console.WriteLine(t.Content as string);
            }
            Console.WriteLine("************");
        }

        void componentBtn_Click(object sender, RoutedEventArgs e)
        {
            Button source = sender as Button;
            if (btnComp != null)
            {
                btnComp.Background = defaultBtnBG;
            }
            btnComp = source;
            source.Background = Brushes.Yellow;

            btnCompFd = null;

            gridDish.RowDefinitions[3].Height = new GridLength(150);

            ComboComponentDisplayObject ccdo = (e.Source as Button).DataContext as ComboComponentDisplayObject;
            IngrediantPanel.Children.Clear();

            List<string> ingredients = dataOp.LoadComboItemComponentIngredientNames(ccdo.BelongedComboName, ccdo.ComponentName);
            foreach (var t in ingredients)
            {
                Button tmpBtn = new Button();
                tmpBtn.Height = 50;
                tmpBtn.Width = 130;
                tmpBtn.Content = t;
                tmpBtn.Click += new RoutedEventHandler(compFdBtn_Click);
                IngrediantPanel.Children.Add(tmpBtn);
                if (comboFdSelectedList.Contains(t))
                {
                    btnCompFd = tmpBtn;
                    tmpBtn.Background = Brushes.Orange;
                }
            }
        }

        void compFdBtn_Click(object sender, RoutedEventArgs e)
        {
            Button source = sender as Button;
            if (btnCompFd != null)
            {
                comboFdSelectedList.Remove(btnCompFd.Content as string);
                btnCompFd.Background = defaultBtnBG;
            }
            btnCompFd = source;
            comboFdSelectedList.Add(source.Content as string);
            source.Background = Brushes.Orange;

            foreach (var t in comboFdSelectedList)
            {
                Console.WriteLine(t);
            }
            Console.WriteLine("***************");
        }

        private void orderBtn_Click(object sender, RoutedEventArgs e)
        {

            if (btnCat == null || btnDish == null)
            {
                MessageBox.Show("选单不完整！");
                return;
            }
            Console.WriteLine("*****下单*****");
            Console.Write((btnCat.Content as string) + "(" + (btnCat.DataContext as CategoryDishplayObject).BelongedType + ")--->" + (btnDish.Content as AccessText).Text);
            switch ((btnCat.DataContext as CategoryDishplayObject).BelongedType)
            {
                case "Combo":
                    {
                        for (int i = 0; i < totalSelection; i++)
                        {
                            if (selectedFdBtn[i] == null)
                            {
                                MessageBox.Show("选单不完整!");
                                return;
                            }
                        }
                        comboFdSelectedList = new List<string>();
                        for (int i = 0; i < totalSelection; i++)
                        {
                            comboFdSelectedList.Add((selectedFdBtn[i] as Button).Content as string);
                        }
                        if (comboFdSelectedList == null || comboFdSelectedList.Count != compNum)
                        {
                            MessageBox.Show("选单不完整！");
                            return;
                        }
                        Console.Write("--->");
                        foreach (var t in comboFdSelectedList)
                        {
                            Console.Write(t + ", ");
                        }
                        break;
                    }
                case "FixedDish":
                    {
                        break;
                    }
                case "ReplaceableDish":
                    {
                        Console.Write("--->");
                        foreach (var t in btnOpts)
                        {
                            Console.Write((t.Content as string) + ", ");
                        }
                        break;
                    }
            }
            Console.WriteLine("\n*********************");

            string catname = btnCat.Content as string;
            string dishname = (btnDish.Content as AccessText).Text;
            string typeStr = (btnCat.DataContext as CategoryDishplayObject).BelongedType;
            DishType dishtype;
            switch (typeStr)
            {
                case "Combo":
                    {
                        dishtype = DishType.Combo;
                        break;
                    }
                case "FixedDish":
                    {
                        dishtype = DishType.FixedDish;
                        break;
                    }
                case "ReplaceableDish":
                    {
                        dishtype = DishType.Replaceable;
                        break;
                    }
                default:
                    {
                        dishtype = DishType.None;
                        break;
                    }
            }

            BillItem item = new BillItem()
            {
                categoryName = catname,
                dishName = dishname,
                dishType = dishtype
            };
            switch (item.dishType)
            {
                case DishType.Combo:
                    {
                        item.comboDishes = comboFdSelectedList;
                        ComboObject tmpComboObj = (from c in dataOp.LoadComboObjects()
                                                   where c.ObjectName == item.dishName
                                                   select c).First();
                        if (tmpComboObj.PriceType == PriceType.FixedPrice)
                        {
                            item.Price = tmpComboObj.Price;
                        }
                        else
                        {
                            decimal tmpPrice = 0.0M;
                            foreach (var t in comboFdSelectedList)
                            {
                                tmpPrice += (from c in dataOp.LoadFixedDishObjects()
                                             where c.ObjectName == t
                                             select c).First().Price;
                            }
                            item.Price = tmpPrice;
                            item.Price -= tmpComboObj.Price;
                        }
                        break;
                    }
                case DishType.Replaceable:
                    {
                        item.options = (from c in btnOpts
                                        select (c.Content as string)).ToList();
                        item.Price = (from c in dataOp.LoadReplaceableDishObjects()
                                      where c.ObjectName == item.dishName
                                      select c).First().Price;
                        break;
                    }
                case DishType.FixedDish:
                    {
                        item.Price = (from c in dataOp.LoadFixedDishObjects()
                                      where c.ObjectName == item.dishName
                                      select c).First().Price;
                        break;
                    }
                default:
                    {
                        MessageBox.Show("账单项类型有误！请联系开发人员");
                        break;
                    }
            }
            totalLabel.Content = (Convert.ToDecimal((totalLabel.Content as string)) + item.Price).ToString();
            actualLabel.Content = (Convert.ToDecimal(totalLabel.Content as string) - Convert.ToDecimal(discountLabel.Content as string)).ToString("F2");
            item.getDishplayName();
            //item.getPrice();
            billItemList.Add(item);
            gridDish.RowDefinitions[2].Height = new GridLength(0);
            gridDish.RowDefinitions[3].Height = new GridLength(0);
            for (int i = 4; i < 9; i++)
            {
                gridDish.RowDefinitions[i].Height = new GridLength(0);
                selectedFdBtn[i - 4] = null;
            }
            dishBtnsPanel.Children.Clear();

            btnCat.Background = defaultBtnBG;
            btnCat = null;
            btnDish = null;
            btnComp = null;
            btnOpts = null;
            comboFdSelectedList = null;
            compNum = 0;
        }


        private void btnPayment_Click(object sender, RoutedEventArgs e)
        {
            if (Convert.ToDecimal(returnLabel.Content as string) < 0.00M)
            {
                MessageBox.Show("未给足餐款，无法结账");
                return;
            }
            string btnColor = "无牌";
            if (waitingCardBtn.Background.Equals(Brushes.Red))
            {
                btnColor = "红" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Yellow))
            {
                btnColor = "黄" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Blue))
            {
                btnColor = "蓝" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Green))
            {
                btnColor = "绿" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Orange))
            {
                btnColor = "橙" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.White))
            {
                btnColor = "白" + (waitingCardBtn.Content as string);
            }

            string eatPlaceResult = eatPlaceBtn.Content as string;
            
            //EatPlaceWindow eatPlaceWin = new EatPlaceWindow();
            //eatPlaceWin.Owner = this;
            //eatPlaceWin.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            //if (eatPlaceWin.ShowDialog() != true)
            //{
            //    return;
            //}
            //插入点单信息
            int billid = dataOp.AddBill(billItemList.ToList(), user.LogID, Convert.ToDecimal(discountLabel.Content as string), eatPlaceResult, cashierip);
            //增加收银员的余额(应收价格)
            dataOp.AddCashierMenoy(user.LogID, Convert.ToDecimal(actualLabel.Content));

            BillInfo bi = new BillInfo();
            bi.BillItems = new System.Collections.ArrayList();

            //win.Connect(user.StaffName);
            System.Collections.Generic.List<string> tmpDishes = new List<string>();

            BillHistory tmpBillHistory = new BillHistory();
            string printInfo = string.Empty;
            string toKitchen = string.Empty;
            string nowTime = DateTime.Now.ToLongTimeString();
            printInfo = "           正味轩餐厅\n订单号：" + billid.ToString()
                + "\n标识：" + firsttime
                + "\n时间：" + nowTime
                + "\n餐牌：" + btnColor + "     送餐类型：" + eatPlaceResult
                + "\n" + "--------------------------------\n";
            foreach (var t in billItemList)
            {
                tmpDishes.Add(t.DisplayName);
                BillItemHistory tmpBIH = new BillItemHistory()
                {
                    DishName = t.DisplayName,
                    DishPrice = t.Price
                };
                tmpBillHistory.BillItems.Add(tmpBIH);
                printInfo += "品名：" + t.DisplayName + "\n" + "价格：" + t.Price + "\n";
                toKitchen += "\n单号：" + billid.ToString() + "  时间：" + nowTime + "  机号：" + cashierip.Substring(cashierip.Length - 3) + "\n" + eatPlaceResult + "，" + btnColor + "，" + t.DisplayName + "\n";
                //dataOp.AddKitchenBillItem(billid, eatPlaceWin.plaseResult + "，" + btnColor + "，" + t.DisplayName);

            }
            Console.WriteLine(toKitchen);
            printInfo += "--------------------------------\n";
            printInfo += "总价：" + (totalLabel.Content as string) + "    优惠：" + (discountLabel.Content as string) + "\n";
            printInfo += "应收：" + (actualLabel.Content as string) + "    实收：" + (recieveLabel.Content as string) + "\n找补：" + (returnLabel.Content as string) + "\n";
            printInfo += "         谢谢惠顾\n\n";
            Console.WriteLine(printInfo);


            dataOp.AddKitchenBill(billid, "标号 "+firsttime+" 对应单号 "+billid+"\n------------------", btnColor, eatPlaceResult);

            BillHistoryList.Add(tmpBillHistory);

            PosPrinter.POSPrinter printer = new PosPrinter.POSPrinter();
            printer.OpenBox();


            waitingCardBtn.Background = defaultBtnBG;
            waitingCardBtn.Content = "餐牌";
            billItemList.Clear();
            totalLabel.Content = "0.00";
            recieveLabel.Content = "0.00";
            returnLabel.Content = "0.00";
            discountLabel.Content = "0.00";
            actualLabel.Content = "0.00";
            //returnLabel.Content = string.Empty;
            //recieveLabel.Content = string.Empty;
            btnPayment.IsEnabled = false;
            printer.PrintLine(printInfo);
            eatPlaceBtn.Content = "送餐地点";
        }

        private void btnRecieve_Click(object sender, RoutedEventArgs e)
        {
            if (billItemList.Count == 0)
            {
                return;
            }
            NumbericPad numPad = new NumbericPad();
            numPad.Owner = this;
            numPad.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (numPad.ShowDialog() == true)
            {
                decimal total = Convert.ToDecimal(totalLabel.Content as string);
                recieveLabel.Content = Convert.ToDecimal(numPad.numStr).ToString("F2");
                decimal recieve = Convert.ToDecimal(numPad.numStr);
                decimal discount = Convert.ToDecimal(discountLabel.Content as string);
                returnLabel.Content = (recieve - total + discount).ToString("F2");
                btnPayment.IsEnabled = true;
            }

            XElement xmlfile = XElement.Load("MoneyBox.xml");
            decimal rest = Convert.ToDecimal(xmlfile.Element("Rest").Value);
            rest += Convert.ToDecimal(actualLabel.Content as string);
            xmlfile.Element("Rest").Value = rest.ToString();
            xmlfile.Save("MoneyBox.xml");
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Owner.Show();
        }


        private void btnDelSelected_Click(object sender, RoutedEventArgs e)
        {
            if (listViewBill.SelectedItem != null)
            {
                decimal thisprice = (listViewBill.SelectedItem as BillItem).Price;
                totalLabel.Content = (Convert.ToDecimal((totalLabel.Content as string)) - thisprice).ToString();
                billItemList.Remove(listViewBill.SelectedItem as BillItem);
            }
        }

        private void btnDelAll_Click(object sender, RoutedEventArgs e)
        {
            billItemList.Clear();
            totalLabel.Content = "0.00";
        }

        private void btnViewHistory_Click(object sender, RoutedEventArgs e)
        {
            if (BillHistoryList.Count < 0)
            {
                return;
            }
            BillHistoryWindow win = new BillHistoryWindow(BillHistoryList, cashierip);
            win.Owner = this;
            win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            win.ShowDialog();
        }

        private void btnSelectedCancel_Click(object sender, RoutedEventArgs e)
        {
            gridDish.RowDefinitions[2].Height = new GridLength(0);
            gridDish.RowDefinitions[3].Height = new GridLength(0);
            for (int i = 4; i < 9; i++)
            {
                gridDish.RowDefinitions[i].Height = new GridLength(0);
                selectedFdBtn[i - 4] = null;
            }
            dishBtnsPanel.Children.Clear();

            if (btnCat != null)
            {
                btnCat.Background = defaultBtnBG;
            }
            btnCat = null;
            btnDish = null;
            btnComp = null;
            btnOpts = null;
            comboFdSelectedList = null;
            compNum = 0;
        }

        private void btnSelectedUp_Click(object sender, RoutedEventArgs e)
        {
            if (listViewBill.SelectedIndex > -1)
            {
                listViewBill.SelectedIndex--;
            }
        }

        private void btnSeletedDown_Click(object sender, RoutedEventArgs e)
        {
            if (listViewBill.SelectedIndex < (listViewBill.Items.Count - 1))
            {
                listViewBill.SelectedIndex++;
            }
        }

        private void BtnWaitingCard_Click(object sender, RoutedEventArgs e)
        {
            WaitingCards win = new WaitingCards(waitingCardBtn);
            win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            win.ShowDialog();
        }

        private void btnHere_CLick(object sender, RoutedEventArgs e)
        {
            order("堂食");
        }

        private void btnOut_Click(object sender, RoutedEventArgs e)
        {
            order("打包");
        }

        private void order(string whereEat)
        {

            if (btnCat == null || btnDish == null)
            {
                MessageBox.Show("选单不完整！");
                return;
            }
            if ((eatPlaceBtn.Content as string).Equals("送餐地点"))
            {
                MessageBox.Show("请选择送餐地点");
                return;
            }


            Console.WriteLine("*****下单*****");
            Console.Write((btnCat.Content as string) + "(" + (btnCat.DataContext as CategoryDishplayObject).BelongedType + ")--->" + (btnDish.Content as AccessText).Text);
            switch ((btnCat.DataContext as CategoryDishplayObject).BelongedType)
            {
                case "Combo":
                    {
                        for (int i = 0; i < totalSelection; i++)
                        {
                            if (selectedFdBtn[i] == null)
                            {
                                MessageBox.Show("选单不完整!");
                                return;
                            }
                        }
                        comboFdSelectedList = new List<string>();
                        for (int i = 0; i < totalSelection; i++)
                        {
                            comboFdSelectedList.Add((selectedFdBtn[i] as Button).Content as string);
                        }
                        if (comboFdSelectedList == null || comboFdSelectedList.Count != compNum)
                        {
                            MessageBox.Show("选单不完整！");
                            return;
                        }
                        Console.Write("--->");
                        foreach (var t in comboFdSelectedList)
                        {
                            Console.Write(t + ", ");
                        }
                        break;
                    }
                case "FixedDish":
                    {
                        break;
                    }
                case "ReplaceableDish":
                    {
                        Console.Write("--->");
                        foreach (var t in btnOpts)
                        {
                            Console.Write((t.Content as string) + ", ");
                        }
                        break;
                    }
            }
            Console.WriteLine("\n*********************");

            string catname = btnCat.Content as string;
            string dishname = (btnDish.Content as AccessText).Text;
            string typeStr = (btnCat.DataContext as CategoryDishplayObject).BelongedType;
            DishType dishtype;
            switch (typeStr)
            {
                case "Combo":
                    {
                        dishtype = DishType.Combo;
                        break;
                    }
                case "FixedDish":
                    {
                        dishtype = DishType.FixedDish;
                        break;
                    }
                case "ReplaceableDish":
                    {
                        dishtype = DishType.Replaceable;
                        break;
                    }
                default:
                    {
                        dishtype = DishType.None;
                        break;
                    }
            }

            BillItem item = new BillItem()
            {
                categoryName = catname,
                dishName = dishname,
                dishType = dishtype
            };
            switch (item.dishType)
            {
                case DishType.Combo:
                    {
                        item.comboDishes = comboFdSelectedList;
                        ComboObject tmpComboObj = (from c in dataOp.LoadComboObjects()
                                                   where c.ObjectName == item.dishName
                                                   select c).First();
                        if (tmpComboObj.PriceType == PriceType.FixedPrice)
                        {
                            item.Price = tmpComboObj.Price;
                        }
                        else
                        {
                            decimal tmpPrice = 0.0M;
                            foreach (var t in comboFdSelectedList)
                            {
                                tmpPrice += (from c in dataOp.LoadFixedDishObjects()
                                             where c.ObjectName == t
                                             select c).First().Price;
                            }
                            item.Price = tmpPrice;
                            item.Price -= tmpComboObj.Price;
                        }
                        break;
                    }
                case DishType.Replaceable:
                    {
                        item.options = (from c in btnOpts
                                        select (c.Content as string)).ToList();
                        item.Price = (from c in dataOp.LoadReplaceableDishObjects()
                                      where c.ObjectName == item.dishName
                                      select c).First().Price;
                        break;
                    }
                case DishType.FixedDish:
                    {
                        item.Price = (from c in dataOp.LoadFixedDishObjects()
                                      where c.ObjectName == item.dishName
                                      select c).First().Price;
                        break;
                    }
                default:
                    {
                        MessageBox.Show("账单项类型有误！请联系开发人员");
                        break;
                    }
            }
            string btnColor = "无牌";
            if (waitingCardBtn.Background.Equals(Brushes.Red))
            {
                btnColor = "红" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Yellow))
            {
                btnColor = "黄" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Blue))
            {
                btnColor = "蓝" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Green))
            {
                btnColor = "绿" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.Orange))
            {
                btnColor = "橙" + (waitingCardBtn.Content as string);
            }
            else if (waitingCardBtn.Background.Equals(Brushes.White))
            {
                btnColor = "白" + (waitingCardBtn.Content as string);
            }
            if (billItemList.Count == 0)
            {
                var thistime = DateTime.Now;
                firsttime = cashierip.Substring(cashierip.Length - 3) + thistime.ToString(" yyyyMMdd HH:mm:ss") + "-" + (eatPlaceBtn.Content as string) + "-" + btnColor + "-";
            }
            totalLabel.Content = (Convert.ToDecimal((totalLabel.Content as string)) + item.Price).ToString();
            actualLabel.Content = (Convert.ToDecimal(totalLabel.Content as string) - Convert.ToDecimal(discountLabel.Content as string)).ToString("F2");
            item.getDishplayName();
            item.DisplayName = "（" + whereEat + "）" + item.DisplayName;
            //item.getPrice();
            billItemList.Add(item);
            dataOp.AddKitchenBillItem(0, firsttime + item.DisplayName);
            gridDish.RowDefinitions[2].Height = new GridLength(0);
            gridDish.RowDefinitions[3].Height = new GridLength(0);
            for (int i = 4; i < 9; i++)
            {
                gridDish.RowDefinitions[i].Height = new GridLength(0);
                selectedFdBtn[i - 4] = null;
            }
            dishBtnsPanel.Children.Clear();

            btnCat.Background = defaultBtnBG;
            btnCat = null;
            btnDish = null;
            btnComp = null;
            btnOpts = null;
            comboFdSelectedList = null;
            compNum = 0;
            
        }

        private void btnDiscount_Click(object sender, RoutedEventArgs e)
        {
            NumbericPad numPad = new NumbericPad();
            numPad.Owner = this;
            numPad.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (numPad.ShowDialog() == true)
            {
                discountLabel.Content = Convert.ToDecimal(numPad.numStr).ToString("F2") ;
            }
            actualLabel.Content = (Convert.ToDecimal(totalLabel.Content as string) - Convert.ToDecimal(discountLabel.Content as string)).ToString("F2");
        }

        private void BtnSellOff_Click(object sender, RoutedEventArgs e)
        {
            SellOffWindow win = new SellOffWindow(sellOffList);
            win.Owner = this;
            win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            win.ShowDialog();
        }

        private void eatPlaceBtn_Click(object sender, RoutedEventArgs e)
        {
            EatPlaceWindow win = new EatPlaceWindow();
            win.Owner = this;
            win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (win.ShowDialog() == true)
            {
                eatPlaceBtn.Content = win.plaseResult;
            }
        }

    }
}
